package com.shisfish.library.Controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.json.JSONArray;

import com.shisfish.library.Impl.BookLendImpl;
import com.shisfish.library.Impl.TestImpl;
import com.shisfish.library.Model.Book;
import com.shisfish.library.Model.BookLend;
import com.shisfish.library.Model.BookSingle;
import com.shisfish.library.Model.Test;
import com.shisfish.library.Model.User;
import com.shisfish.library.Prere.GetSysMailbox;
import com.shisfish.library.Utils.CacheUtils;
import com.shisfish.library.Utils.ExcelToBean;
import com.shisfish.library.Utils.JsonValueUtil;
import com.shisfish.library.Utils.NameToLetterUtils;
import com.shisfish.library.Utils.SendEmailUtils;
import com.shisfish.library.Utils.FileUpload.FileUploadUtils;
import com.shisfish.library.Utils.FileUpload.FormJsonArrUtil;
import com.shisfish.library.Utils.Global.GlobalVariable;
import com.shisfish.library.Utils.Global.toJsonUtils;

@Path("test")
public class TestController extends GlobalVariable{

	
	@GET	
	@Path("selectAll")
	@Produces("application/json; charset=utf-8")
	public String selectAll(){
		Map<String, Object> globalMap = new HashMap<String, Object>();
		List<Test> tests = new TestImpl().selectAll();

		globalMap.put("list", tests);
		
		String jsonString = toJsonUtils.map2Json(globalMap);
		//String jsonString = toJsonUtils.list2Json(tests);
		return jsonString;
	}
	
	@POST	
	@Path("insertOne")
	@Produces("application/json; charset=utf-8")
	public String insertOne(@FormParam("name") String name){
		String str = "";
		
		for (int i = 0, len = name.length(); i < len; i++) {
			str += NameToLetterUtils.convert(name.charAt(i)+"");
		}
		
		Test test = new Test(name, str);

		int flag = new TestImpl().insertOne(test);

		System.out.println(flag);
		
		return flag+"";
	}
	
	@POST
	@Path("insertAll")
	@Produces("application/json; charset=utf-8")
	public String insertAll(){
		/*String[] names = name.split(",");
		List<String> namelist = Arrays.asList(names);
		CHOMAP.put("key", namelist);*/
		
		List<Test> testlist = new ArrayList<Test>();
		
		for (int i = 0; i < 10; i++) {
			Test test = new Test();
			test.setName(i+"");
			testlist.add(test);
		}
		
		int flag = new TestImpl().insertAll(testlist);

		System.out.println(flag);
		
		return flag+"";
	}
	
	@POST	
	@Path("updateOne")
	@Produces("application/json; charset=utf-8")
	public String updateOne(@FormParam("name") String name){
		List<Test> tests = new TestImpl().selectByKey(name);
		int flag = 0;
		if (tests.size() > 0) {
			Test test = tests.get(0);
			test.setDeleteStatus(1);
			flag = new TestImpl().updateOne(test);
			
		}

		System.out.println(flag);
		
		return flag+"";
	}
	
	@POST	
	@Path("updateAll")
	@Produces("application/json; charset=utf-8")
	public String updateAll(){
		List<Test> tests = new TestImpl().selectAll();
		int flag = 0;
		if (tests.size() > 0) {
			for (Test test : tests) {
				test.setDeleteStatus(1);
			}
			flag = new TestImpl().updateAll(tests);
		}

		System.out.println(flag);
		
		return flag+"";
	}
	
	@POST	
	@Path("deleteOneById")
	@Produces("application/json; charset=utf-8")
	public String deleteOneById(@FormParam("id") int id){
		int flag = new TestImpl().deleteOneById(id);
		
		System.out.println(flag);
		
		return flag + "";
	}
	
	@POST	
	@Path("deleteOneByKey")
	@Produces("application/json; charset=utf-8")
	public String deleteOneByKey(@FormParam("name") String name){
		int flag = new TestImpl().deleteOneByKey(name);
		
		System.out.println(flag);
		
		return flag + "";
	}
	
	@POST	
	@Path("deleteAllById")
	@Produces("application/json; charset=utf-8")
	public String deleteAllById(@FormParam("id") String id){
		String[] ids = id.split(",");
		List<String> idlist = Arrays.asList(ids);
		int flag = new TestImpl().deleteAllById(idlist);
		
		System.out.println(flag);
		
		return flag + "";
	}
	
	@POST	
	@Path("deleteAllByKey")
	@Produces("application/json; charset=utf-8")
	public String deleteAllByKey(@FormParam("name") String name){
		String[] names = name.split(",");
		List<String> namelist = Arrays.asList(names);
		int flag = new TestImpl().deleteAllByKey(namelist);
		
		System.out.println(flag);
		
		return flag + "";
	}
	
	@POST
	@Path("excelInsert")
	@Consumes({MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_JSON})
	@Produces(MediaType.TEXT_PLAIN)
	public String excelInsert(@Context HttpServletRequest request) throws Exception {
			FileUploadUtils fuu = new FileUploadUtils();
			JsonValueUtil jvu = new JsonValueUtil();
			// 从缓存中取得配置文件的学生文件保存服务器路径
			// String path = CommonUtils.getIorfUrl(Constants.ADMIN_FILE_URL,
			// request);
			String path = "d:\\";
			fuu.setFilePath(path);
			// 取得所有文件和表单值 并保存文件至本地
			JSONArray jsArr = fuu.getRiverWayUpload(request);
			// 取得所有普通表单值
			// customjsArr= filejsArr= new
			// FormJsonArrUtil().getFormJsonArr(jsArr, "custom");
			JSONArray filejsArr = new FormJsonArrUtil().getFormJsonArr(jsArr, "file");

			ExcelToBean<Test> util = new ExcelToBean<Test>();
			// 取得文件保存路径 "form_picture" 为前台表单name 值必须一样
			String excelFilePath = path
					+ jvu.getValue(filejsArr, "form_picture");

			// 将上传的表格转换成List
			String configFilePath = request.getSession().getServletContext().getRealPath("/") + File.separator
					+ "excelModel/test.xml";
			List<Test> tests = new ArrayList<Test>();
			try {
				tests = util.parseExcelFileToBeans(new File(excelFilePath),
						new File(configFilePath));
				
				int flag = new TestImpl().insertAll(tests);
				System.out.println(flag);
				
			} catch (Exception e) {
				return "{\"message\":\"excel 表格有误\",\"statusCode\": \"500\"}";
			}
			return "{\"message\":\"success\",\"statusCode\": \"200\"}";
		
	}
	
	@GET
	@Path("toCache")
	@Produces("application/json; charset=utf-8")
	public String toCache(@Context HttpServletRequest request) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		CacheManager cacheManager = CacheUtils.getCacheManger(request);
		
		Cache cache = cacheManager.getCache("admin_login");
		
		Element element = new Element("idcard", "1212800117");
		
		cache.put(element);
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	@GET
	@Path("getCache")
	@Produces("application/json; charset=utf-8")
	public String getCache(@Context HttpServletRequest request) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		CacheManager cacheManger = CacheUtils.getCacheManger(request);
		
		Cache cache = cacheManger.getCache("admin_login");
		
		Element element = cache.get("idcard");
		
		System.out.println(element.getObjectKey());
		
		System.out.println(element.getObjectValue());
		
		globalMap.put("xuehao", element.getObjectValue());
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	@GET
	@Path("testst")
	@Produces("application/json; charset=utf-8")
	public String testst() {
		List<BookLend> bookLends = new BookLendImpl().selectRemind(5);
		
		if (bookLends.size() > 0) {
			
			// 找到全部的过期用户对象
			Set<String> borrowers = new HashSet<String>();
			for (int i = 0, len = bookLends.size(); i < len; i++) {
				borrowers.add(bookLends.get(i).getBorrower());
			}
			
			// 单个用户一条数据
			List<HashMap<String, Object>> overdue = new ArrayList<HashMap<String, Object>>();
			for (String string : borrowers) {
				List<Book> books = new ArrayList<Book>();
				List<BookSingle> bookSingles = new ArrayList<BookSingle>();
				List<BookLend> bookLendss = new ArrayList<BookLend>();
				for (int i = 0, len = bookLends.size(); i < len; i++) {
					if (bookLends.get(i).getBorrower().equals(string)) {
						books.add(bookLends.get(i).getBook());
						bookSingles.add(bookLends.get(i).getBookSingle());
						bookLendss.add(bookLends.get(i));
					}
				}
				HashMap<String, Object> temp = new HashMap<String, Object>();
				temp.put("borrowers", string);
				temp.put("books", books);
				temp.put("bookSingles", bookSingles);
				temp.put("bookLendss", bookLendss);
				overdue.add(temp);
			}
			
			// 把用户信息添加进去
			for (HashMap<String, Object> hashMap : overdue) {
				for (int i = 0, len = bookLends.size(); i < len; i++) {
					User user = bookLends.get(i).getUser();
					if (hashMap.get("borrowers").equals(user.getEmployee())) {
						hashMap.put("user", user);
						break;
					}
				}
			}
			
			for (HashMap<String, Object> hashMap : overdue) {
				User user = (User) hashMap.get("user");
				if (!"".equals(user.getEmail())) {
					
					StringBuffer sb1 = new StringBuffer();
					sb1.append("<strong><center>图书馆图书到期通知</center></strong><br>");
					sb1.append("<table style='align:left;width:100%'>");
					sb1.append(" 用户名为 <b>["+user.getUsername()+"]</b>  的读者   您好：");
					sb1.append("<table cellpadding='0' cellspacing='0'>");
					sb1.append("<tbody><tr><td colspan='7'><b style='color:#666666;font-size: 14px;' >到期提醒</b></td></tr>");
					sb1.append("<tr>");
					sb1.append("<td style='background-color:#5F9EA0;color:#ffffff;font-size:12px;font-weight:bold;text-indent:8px ;'>题名</td>");
					sb1.append("<td style='background-color:#5F9EA0;color:#ffffff;font-size:12px;font-weight:bold;text-indent:8px ;'>作者</td>");
					sb1.append("<td style='background-color:#5F9EA0;color:#ffffff;font-size:12px;font-weight:bold;text-indent:8px ;'>还书处</td>");
					sb1.append("<td style='background-color:#5F9EA0;color:#ffffff;font-size:12px;font-weight:bold;text-indent:8px ;'>条码号</td>");
					sb1.append("<td style='background-color:#5F9EA0;color:#ffffff;font-size:12px;font-weight:bold;text-indent:8px ;'>分类号</td>");
					sb1.append("<td style='background-color:#5F9EA0;color:#ffffff;font-size:12px;font-weight:bold;text-indent:8px ;'>应还日期</td>");
					sb1.append("</tr>");
					
					@SuppressWarnings("unchecked")
					ArrayList<Book> books = (ArrayList<Book>) hashMap.get("books");
					@SuppressWarnings("unchecked")
					ArrayList<BookLend> bookLendss = (ArrayList<BookLend>) hashMap.get("bookLendss");
					@SuppressWarnings("unchecked")
					ArrayList<BookSingle> bookSingles = (ArrayList<BookSingle>) hashMap.get("bookSingles");
					
					for (int i = 0, len = books.size(); i < len; i++) {
						sb1.append("<tr");
						sb1.append("<td style='background-color:#eeeeee;color:#666666;font-size:12px;text-indent:8px;border:0px solid #ffffff;'>《"+books.get(i).getTitle()+"》</td>");
						sb1.append("<td style='background-color:#eeeeee;color:#666666;font-size:12px;text-indent:8px;border:0px solid #ffffff;'>"+books.get(i).getAuthor()+"</td>");
						sb1.append("<td style='background-color:#eeeeee;color:#666666;font-size:12px;text-indent:8px;border:0px solid #ffffff;'>"+bookSingles.get(i).getPosition()+"</td>");
						sb1.append("<td style='background-color:#eeeeee;color:#666666;font-size:12px;text-indent:8px;border:0px solid #ffffff;'>"+bookSingles.get(i).getBarCode()+"</td>");
						sb1.append("<td style='background-color:#eeeeee;color:#666666;font-size:12px;text-indent:8px;border:0px solid #ffffff;'>"+books.get(i).getCategory()+"</td>");
						sb1.append("<td style='background-color:#eeeeee;color:#666666;font-size:12px;text-indent:8px;border:0px solid #ffffff;'>"+bookLendss.get(i).getShouldReturnTime()+"</td>");
						sb1.append("</tr>");
					}

					
					sb1.append("</tbody></table>");
					sb1.append("</table>");
					sb1.append("<div style='font-size: 12px;color: darkgray; font-weight: 100;'><font>信件内容是"+new Date()+"生成的，可能存在延时，仅作提示使用，一切信息皆以您在图书馆实际情况为准。<br>");
					sb1.append("这封信是由图书馆应用服务系统自动发送的。如有任何问题，请与我们的工作人员联系。</font></div>");
					
					String[] str = GetSysMailbox.getSysMailbox();
					String to = user.getEmail();
					String subject = "你有" + books.size() + "即将超期或已经超期！";
					System.out.println("++++++++++++" + to);
					System.out.println("++++++++++++" + subject);
					SendEmailUtils.sendEmail(to, subject, sb1.toString(), str[0], str[0], str[1]);
				}
			}
			
		} else {
			System.out.println("没有需要提醒的人！");
		}
		return "";	
	}
	
	
}
